//
//  LTNearController.m
//  LocalTravelIPhone
//
//  Created by zheng ji on 14-3-28.
//  Copyright (c) 2014年 jxw. All rights reserved.
//
#define RecordsOfPage 20

#import "LTNearController.h"

@interface LTNearController ()
{
      LTAppDelegate* _appDelegate;
    int _currentPage;//当前页数
    int _totalPage;
    int  _distance;
    UIStoryboard *_storyBoard;
    UIActivityIndicatorView  *_activity;
 NSMutableArray* _arrayScenery;
    GADBannerView* bannerView_;
    MobiSageAdBanner * adBanner;
}
@end

@implementation LTNearController
- (UIViewController *)viewControllerToPresent
{
    return self;
}
-(void)addSageAd{
    adBanner = [[MobiSageAdBanner alloc] initWithAdSize:Ad_320X50 withDelegate:self];
    adBanner.frame = CGRectMake(0, 0, 320, 50);
    [adBanner setInterval:Ad_Refresh_30];
    //设置广告轮播动画效果
    [adBanner setSwitchAnimeType:Random];
    
    [self.collectionView addSubview:adBanner];
}

-(void)addGoogleAdv{
    bannerView_ = [[GADBannerView alloc]
                   initWithFrame:CGRectMake(0.0,
                                            0.0 ,
                                            GAD_SIZE_320x50.width,
                                            GAD_SIZE_320x50.height)];    // 指定广告单元ID。
    
    bannerView_.adUnitID = [CommonConfigUtil getGoogleAdvId];
    
    bannerView_.rootViewController = self;
    [self.collectionView addSubview:bannerView_];
    GADRequest *request = [GADRequest request];
    // request.testDevices = @[ GAD_SIMULATOR_ID ];
    [bannerView_ loadRequest:request];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(adBanner==nil){
        [self addSageAd];
    }
    
    /*
     if(bannerView_ ==nil){
     [self addGoogleAdv];
     }*/

    
}
- (IBAction)segmentValueChanged:(id)sender {
    [_arrayScenery removeAllObjects];
    _currentPage=1;
    _totalPage=0;
   
    [_arrayScenery removeAllObjects];
    [self.collectionView reloadData];
    if(self.segControl.selectedSegmentIndex==0){
       _distance=5000;
        
    }else if(self.segControl.selectedSegmentIndex==1){
        _distance=10000;
    }else if(self.segControl.selectedSegmentIndex==2){
        _distance=15000;
    }
    [self loadData];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
     _currentPage=0;//当前页数
     _totalPage=0;
     _distance=0;
        _arrayScenery=[[NSMutableArray alloc] init];
     _appDelegate=[[UIApplication sharedApplication] delegate];
    
       [self.collectionView registerNib:[UINib nibWithNibName:@"CollectionCell" bundle:nil] forCellWithReuseIdentifier:@"CollectionCell"];
    
    self.view.backgroundColor=BACKGROUND_COLOR;
    self.collectionView.backgroundColor=[UIColor clearColor];
    self.segControl.selectedSegmentIndex=3;
    
    
    if(_appDelegate.currentPostionlongitude<=0){
       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"未获取到当前位置!"                                                          delegate:nil  cancelButtonTitle:@"确定" otherButtonTitles: nil,nil];
   
       [alert show];
    
        alert=nil;
    }
    
    [self loadData];
    
}
-(void)loadData{
    _currentPage = _currentPage+1;
    
    if(_totalPage==0){
        [self searchScenery:1 pageSize:RecordsOfPage];
    }else if(_currentPage<=_totalPage){
        
        [self searchScenery:_currentPage pageSize:RecordsOfPage];

        
    }
    
    
}
-(void)searchScenery:(int)page pageSize:(int)pageSize{
    
    [self createActivityIndicatorView];
    
    
    
    NSDictionary* dict3=[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",page],@"page",[NSString stringWithFormat:@"%d",pageSize],@"pageSize", nil];
    
    
    [NSThread detachNewThreadSelector:@selector(searchSceneryInBackgroud:) toTarget:self withObject:dict3];
}
-(void)searchSceneryInBackgroud:(NSDictionary*)dict{
    
    if(![CommonConfigUtil checkNetworkReachable]) return ;
    NSString* cityID=_appDelegate.currentCityID;
    
    
    //为空则读取北京的景点
    if(cityID ==nil )
    {
        cityID=@"";
    }

    
    
    NSString* page=[dict objectForKey:@"page"];
    NSString* pageSize=[dict objectForKey:@"pageSize"];
    NSString* xmlData= [LocalTravelRequest searchScenery:cityID themeId:@"" keyWord:@"" longitude:[NSString stringWithFormat:@"%f",_appDelegate.currentPostionlongitude] latitude:[NSString stringWithFormat:@"%f",_appDelegate.currentPostionlatitude] radius:_distance page:[page intValue] pageSize:[pageSize intValue]];
     
  //  NSString* xmlData= [LocalTravelRequest getSceneryListByCityId:cityID page:[page intValue] pageSize:[pageSize intValue]];
    
    [self performSelectorOnMainThread:@selector(parseData:) withObject:xmlData waitUntilDone:NO];
    //[self parseData:xmlData  cityID:cityID];
    
    
    
    
}
-(void) parseData:(NSString*)xmlData{
    SceneryListParse* parse=[[SceneryListParse alloc]initWithXmlData:xmlData];
    
    NSMutableDictionary* dictRet=[parse getScenaryList];
    if(dictRet!=nil){
        
        NSString* strTotalPage  =[dictRet objectForKey:@"totalPage"];
        _totalPage=[strTotalPage intValue];
        
        NSMutableArray* newArray=[dictRet objectForKey:@"sceneryArray"];
        
        parse=nil;
        if( _arrayScenery.count==0){
            [_arrayScenery addObjectsFromArray:newArray];
            [self.collectionView reloadData];
        }else{
            int count=_arrayScenery.count;
            [self.collectionView performBatchUpdates:^{
                [_arrayScenery addObjectsFromArray:newArray];
                
                NSMutableArray* arrayIndexPath=[NSMutableArray array];
                for (int i=0; i<newArray.count; i++) {
                    
                    [arrayIndexPath addObject:[NSIndexPath indexPathForItem:count+i inSection:0]];
                }
                // [self.collectionView reloadData];
                [self.collectionView insertItemsAtIndexPaths:arrayIndexPath];
                
            } completion:nil];
            
            
        }
        
        
    }
    [self removeActivityIndicatorView];
}

-(void)createActivityIndicatorView{
    _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
	_activity.center = self.view.center;
	_activity.hidesWhenStopped = TRUE;
	[self.view addSubview:_activity];
	[_activity startAnimating];
    
}
-(void)removeActivityIndicatorView{
    [_activity stopAnimating];
    [_activity removeFromSuperview];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if(_arrayScenery !=nil) return _arrayScenery.count;
    
    return 0;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
	return CGSizeMake(134,152);
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CollectionCell* cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCell" forIndexPath:indexPath];
    if(_arrayScenery !=nil && _arrayScenery.count>indexPath.row){
        NSDictionary* dict=[_arrayScenery objectAtIndex:indexPath.row];
        cell.lblTitle.text=[dict objectForKey:@"sceneryName"];
        cell.lblPrice.text=[NSString stringWithFormat:@"最低价:¥ %@",[dict objectForKey:@"amountAdv"]];
        
        
        // cell.imageView.imageUrl=[dict objectForKey:@"imgPath"];
        NSString* imageName=[dict objectForKey:@"imgPath"];
        
        NSString* netImagePath=[NSString stringWithFormat:@"%@160_120/%@",[CommonConfigUtil getTongChenImageBaseUrl],imageName];
        cell.imageView.imageUrl=netImagePath;
        //cell.imageView.imageUrl=netImagePath;
        //cell.imageView.im
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(_arrayScenery ==nil || _arrayScenery.count<indexPath.row) return ;
    
    if(_storyBoard==nil){
        _storyBoard=[UIStoryboard storyboardWithName:@"second" bundle:nil];
    }
    UINavigationController* navi=   [_storyBoard instantiateViewControllerWithIdentifier:@"NaviDetailController"];
    
    LTSceneryDetailController* vc=[navi.viewControllers objectAtIndex:0];
    vc.dictScenery=[_arrayScenery objectAtIndex:indexPath.row];
    // NSString* des=[vc.dictScenery objectForKey:@"scenerySummary"];
    [self presentViewController:navi animated:YES completion:nil];
    
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(60, 15, 15, 15);
}

- (void)scrollViewDidScroll:(UIScrollView*)scrollViewDrag {
    
    CGPoint offset = self.collectionView.contentOffset;
    CGRect bounds = self.collectionView.bounds;
    CGSize size = self.collectionView.contentSize;
    UIEdgeInsets inset = self.collectionView.contentInset;
    CGFloat currentOffset = offset.y + bounds.size.height -inset.bottom;
    CGFloat maximumOffset = size.height;
    if(maximumOffset==currentOffset){
        //加载更多数据
        [self loadData];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc{
    adBanner=nil;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
